package tx_service

import (
	"github.com/sirupsen/logrus"
	"go-blockchain-from-scratch/constants"
	"go-blockchain-from-scratch/database"
	"go-blockchain-from-scratch/mapper"
	"go-blockchain-from-scratch/service/state_service"
	"go.mongodb.org/mongo-driver/bson"
)

func Apply(tx database.Tx) bool {
	state := new(database.State)
	err := mapper.SelectOne(constants.DataBase, constants.StateCollection, bson.M{"account": tx.From}, state)
	if err != nil {
		return false
	}
	//判断余额是不是够
	return state.Balances >= tx.Value
}

func InsertTx(tx database.Tx) {
	if tx.IsReward() {
		//更新from
		state_service.UpdateOrSaveState(tx.From, int(tx.Value), tx)
		//插入tx
		mapper.InsertOne(constants.DataBase, constants.TxCollection, tx)
		return
	}
	if !Apply(tx) {
		logrus.Error("account is not enough")
		return
	}
	//更新from
	state_service.UpdateOrSaveState(tx.From, int(-tx.Value), tx)
	// 插入tx
	mapper.InsertOne(constants.DataBase, constants.TxCollection, tx)
	//更新to
	state_service.UpdateOrSaveState(tx.To, int(tx.Value), tx)

}
